package de.lulusoft.anothertorrent.core.rtorrent;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;

/**
 * This class holds all files of a torrent. When a file is added to a torrent
 * via Torrent.addFile then this class is added as PropertyChangeListener to the 
 * file. Gui elements should add themself as PropertyChangeListener to this class
 * so they get notified when an update of a file in this list occurred.
 * @author 
 *
 */
public class TrackerArrayList extends ArrayList<Tracker> implements PropertyChangeListener{

	private static final long serialVersionUID = 6853514126040693721L;
	
	public static final String PROP_UPDATED = "UpdatedTrackerProperty";
	private PropertyChangeSupport propertyChangeSupport = null;
	
	protected ArrayList<Tracker> updatedTrackers = null;

	
	
	public TrackerArrayList() {
		super();
		propertyChangeSupport = new PropertyChangeSupport(this);
		updatedTrackers = new ArrayList<Tracker>();
	}

	/**
	 * Notifies all Listeners about the updates of a
	 * previous RTorrentManager.updateFiles call.
	 */
	public void updateGUI()
	{		
		try {
			if (updatedTrackers.size() > 0)
				propertyChangeSupport.firePropertyChange(PROP_UPDATED, null, updatedTrackers);
			updatedTrackers.clear();
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}	


	/**
	 * If a file changed locally, then add it to list of changed files and notify the gui.
	 */
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals(Tracker.PROP_CHANGED))
		{
			if (evt.getSource() instanceof Tracker)
			{
				updatedTrackers.add((Tracker)evt.getSource());
				propertyChangeSupport.firePropertyChange(PROP_UPDATED, null, updatedTrackers);
			}
		}
	}
	
	public void addListener(PropertyChangeListener listener)
	{
		propertyChangeSupport.addPropertyChangeListener(listener);
	}
	
	public void removeListener(PropertyChangeListener listener)
	{
		propertyChangeSupport.removePropertyChangeListener(listener);
	}

}
